package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.listener.ChapterExcelListener;
import com.atguigu.eduservice.mapper.EduChapterMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Mr.Alan
 * @since 2020-08-16
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Resource
    private VodClient vodClient;
    @Resource
    private EduCourseService eduCourseService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeChapterById(String id) {
        List<String> delIds = new ArrayList<>();
        delIds.add(id);
        List<String> ids = super.lambdaQuery().eq(EduChapter::getPid, id).select(EduChapter::getId).list().stream().map(EduChapter::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)) {
            delIds.addAll(ids);
        }
        // 删除章节下的所有视频
        List<String> videoIds = super.lambdaQuery().in(EduChapter::getId, ids).select(EduChapter::getId, EduChapter::getVideoId)
                .list().stream().map(EduChapter::getVideoId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(videoIds)) {
            vodClient.deleteVideoById(videoIds);
        }

        return super.removeByIds(delIds);
    }

    @Override
    public List<EduChapter> listByCourseId(String id) {
        List<EduChapter> list = super.lambdaQuery().eq(EduChapter::getCourseId, id)
                .select(EduChapter::getId, EduChapter::getPid, EduChapter::getCourseId, EduChapter::getTitle,
                        EduChapter::getSort, EduChapter::getVideoId).list();
        if (CollectionUtils.isNotEmpty(list)) {
            List<EduChapter> parents = list.stream()
                    .filter(eduChapter -> eduChapter.getPid().equals("0"))
                    .sorted(Comparator.comparing(EduChapter::getSort)).collect(Collectors.toList());
            for (EduChapter parent : parents) {
                List<EduChapter> children = list.stream().filter(eduChapter -> eduChapter.getPid().equals(parent.getId()))
                        .sorted(Comparator.comparing(EduChapter::getSort)).collect(Collectors.toList());
                parent.setChildren(children);
            }
            list = parents;
        }
        return list;
    }

    @Override
    public void importChapterData(MultipartFile file, EduChapterService eduChapterService, String id) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, ExcelSubjectData.class, new ChapterExcelListener(eduChapterService, id)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20002, "添加课程分类失败");
        }
    }

    @Override
    public Integer getNextSort(String pid, String courseId) {
        return getBaseMapper().getNextSort(pid, courseId);
    }

    @Override
    public boolean removeAll(String id) {

        // 删除所有的视频
        List<String> videoIds = super.lambdaQuery().eq(EduChapter::getCourseId, id).select(EduChapter::getId, EduChapter::getVideoId)
                .list().stream().map(EduChapter::getVideoId).collect(Collectors.toList());
        vodClient.deleteVideoById(videoIds);
        eduCourseService.offShelfCourse(id);
        return super.remove(Wrappers.<EduChapter>lambdaQuery().eq(EduChapter::getCourseId, id));

    }
}
